package cn.openread.starter.utils.cons;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

public abstract class AssertionConcern {

    private String fieldCtx;

    public static void staticCheckNotEmpty(Collection fieldVal, String errorMsg) throws RuntimeException {
        if (CollectionUtils.isEmpty(fieldVal)) {
            throw new RuntimeException(errorMsg);
        }
    }

    public void checkParam(boolean expression, String errorMsg) throws RuntimeException {
        if (expression) {
            throw new RuntimeException(errorMsg);
        }
    }

    public void checkNotNull(Object fieldVal, String errorMsg) throws RuntimeException {
        if (fieldVal == null) {
            throw new RuntimeException(errorMsg);
        }
    }

    public void checkNotBlank(String fieldVal, String errorMsg) throws RuntimeException {
        if (StringUtils.isBlank(fieldVal)) {
            throw new RuntimeException(errorMsg);
        }
    }

    public void checkNotEmpty(Collection fieldVal, String errorMsg) throws RuntimeException {
        if (CollectionUtils.isEmpty(fieldVal)) {
            throw new RuntimeException(errorMsg);
        }
    }

    public <T> void checkEqual(T expected, T actual, String failedMessage, String errorMsg) throws RuntimeException {
        if (expected != actual && !expected.equals(actual)) {
            throw new RuntimeException(errorMsg);
        }
    }


    public final void validate() throws RuntimeException {
        validateThenClearCtx();
    }

    public final void validate(String fieldCtx) throws RuntimeException {
        validateThenClearCtx();
    }

    protected final String fieldCtxFor(String fieldName) {
        return fullFieldName(fieldName);
    }

    private void validateThenClearCtx() throws RuntimeException {
        try {
            this.doValidate();
            this.doBizInit();
        } finally {
            this.fieldCtx = null;
        }
    }

    /**
     * 用户自定义校验规则
     */
    protected abstract void doValidate() throws RuntimeException;

    /**
     * 用户自定义业务初始化
     */
    protected abstract void doBizInit() throws RuntimeException;

    private String fullFieldName(String fieldName) {
        if (fieldCtx().isEmpty()) {
            return fieldName;
        }
        return String.format("%s.%s", fieldCtx(), fieldName);
    }

    private String fieldCtx() {
        return (fieldCtx == null ? "" : fieldCtx);
    }
}